package inabit.inabitcompiler.productions.rule.expressions.arithmetic;

import inabit.compiler.parser.grammar.NonTerminal;
import inabit.compiler.parser.grammar.Production;
import inabit.compiler.parser.grammar.Symbol;
import inabit.compiler.parser.grammar.Terminal;
import inabit.data.expression.arithmetic.ArithmeticExpression;
import inabit.data.expression.arithmetic.MethodExpression;
import inabit.data.expression.arithmetic.VariableExpression;
import inabit.inabitcompiler.lexical.InabitTokenClass;
import inabit.inabitcompiler.parser.InabitSemanticAction;

/**Z  -> id J*/
/**@author Rafael Rocha*/
public class Z_Rule extends Production{

	private Terminal id;
	private NonTerminal J;
	
	public Z_Rule() {
		super("Z");
	}

	@Override
	protected Symbol[] production(final NonTerminal nonTerminal) {
		id = new Terminal(InabitTokenClass.ID);
		J = new NonTerminal("J");
		
		Symbol[] symbols = {
			id,
			J,
			new InabitSemanticAction(nonTerminal) {
				public void execute() throws Exception{
					if(J.code.isEmpty()) {
						nonTerminal.code = addArithmeticExpressionAndGetCode(
								new VariableExpression(
										id.getValue()));
					}else {
						String[] params = J.code.split(",");
						ArithmeticExpression[] paramExp = new ArithmeticExpression[params.length];
						
						for(int i = 0; i < params.length; i++){
							paramExp[i] = getArithmeticExpression(params[i]);
						}
						
						MethodExpression me = new MethodExpression(getMethod(id.getValue()), paramExp);
						
						
						nonTerminal.code = addArithmeticExpressionAndGetCode(me);
					}
				}
			}
		};
		return symbols;
	}

}
